//
//  BRWithdrawalVC.m
//  Kexu
//
//  Created by IOS on 2023/7/31.
//

#import "BRWithdrawalVC.h"
#import "BRMerchantModel.h"

@interface BRWithdrawalVC ()<QMUITextFieldDelegate>

@property (nonatomic,strong) QMUITextField *withdrawalTF;

//@property (nonatomic,strong) QMUILabel *accountL;
@property (nonatomic,strong) QMUILabel *balanceL;

@property (nonatomic,strong) BRWithdrawalAccountModel *cardDto;
@property (nonatomic,strong) QMUIButton *submitBtn;

@end

@implementation BRWithdrawalVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setUI];
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    [self.withdrawalTF becomeFirstResponder];
    
}

- (void)toAllin {
    self.withdrawalTF.text = [NSString stringWithFormat:@"%.2f",self.withdrawalAmount.floatValue];
    
    self.submitBtn.enabled = self.withdrawalAmount.floatValue > 0;
}

- (void)toWithdrawalBalance {
    //去提现
    
    if (self.withdrawalTF.text.length == 0 || self.withdrawalTF.text.floatValue == 0) {
        
        [BRHud showAuto:Localized(@"toast_withdrawalAmountText") inView:self.view];
        return;
    }
    
    NSDecimalNumber *inputPrice = [NSDecimalNumber decimalNumberWithString:self.withdrawalTF.text];
    NSComparisonResult result = [inputPrice compare:self.withdrawalAmount];
    if (result == NSOrderedDescending) {
        
        [BRHud showAuto:Localized(@"toast_withdrawalAmountMax") inView:self.view];
        return;
    }
    
    // 提现请求
    [self.withdrawalTF resignFirstResponder];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString *amount = [self br_replaceText:self.withdrawalTF.text];
    dic[@"amount"] = amount;
    dic[@"branchId"] = USERManager.branchId;
    [[BRRequestManager shared] POST:[BRAPI withdrawalAmount] params:dic succeed:^(NSDictionary * _Nonnull dataDict, NSInteger respCode) {
        
        [BRHud showAutoSuccInView:self.view];
        if (self.succBlock) self.succBlock();
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self pop];
        });
        
    } failed:^(NSInteger code, NSString * _Nonnull errMsg) {
        // 没有权限
        if (code == 21334) {
            WS(weakSelf);
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.navigationController popToRootViewControllerAnimated:YES];
            });
        }
    }];
}


/// 限制输入情况
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (string.length == 0) return YES;
    if (textField.text.length == 0 && ([string containsString:@"."] || [string containsString:@","])) return NO;
    if ([textField.text containsString:@"."] && [string isEqualToString:@"."]) return NO;
    if ([textField.text containsString:@","] && [string isEqualToString:@","]) return NO;
    

    
    return YES;
}

- (void)textChangeValue:(QMUITextField *)textfield {
    
    CGFloat amount = [self br_replaceText:textfield.text].floatValue;
   
    self.submitBtn.enabled = amount > 0;
}

/// 去除【 , 】逗号
- (NSString *)br_replaceText:(NSString *)text {
    if ([text containsString:@","]) {
        text = [text stringByReplacingOccurrencesOfString:@"," withString:@"."];
    }
    
    return text;
}

#pragma mark - UI --
- (void)setUI {
    
    [self br_createTop:Localized(@"shop_withdrawal")];
    
    
    UIView *withdrawalBG = [[UIView alloc] init];
    withdrawalBG.backgroundColor = UIColor.whiteColor;
    withdrawalBG.layer.cornerRadius = 10;
    withdrawalBG.layer.masksToBounds = YES;
    [self.view addSubview:withdrawalBG];
    [withdrawalBG mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.top.offset(kSafeAreaTopHeight + 14);
    }];
    
    QMUILabel *topL = [BRToolsView br_label:Localized(@"shop_withdrawalAmount") textColor:kColorTitle font:[UIFont fontS:14]];
    [withdrawalBG addSubview:topL];
    [topL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(14);
        make.left.offset(20);
    }];
    
    QMUITextField *withdrawalTF = [[QMUITextField alloc] init];
    withdrawalTF.clearButtonMode = UITextFieldViewModeWhileEditing;
    withdrawalTF.clearButtonPositionAdjustment = UIOffsetMake(-20, 0);
    withdrawalTF.textInsets = UIEdgeInsetsMake(0, 40, 0, 40);
    withdrawalTF.placeholderColor = UIColorMakeWithHex(@"#AAAAAC");
    withdrawalTF.font = [UIFont fontM:14];
    withdrawalTF.textColor = kColorTitle;
    withdrawalTF.tintColor = kColorMain;
    withdrawalTF.placeholder = Localized(@"shop_pleaseEnter");
    withdrawalTF.delegate = self;
    withdrawalTF.maximumTextLength = 28;
    withdrawalTF.keyboardType = UIKeyboardTypeDecimalPad;
    [withdrawalBG addSubview:withdrawalTF];
    withdrawalTF.backgroundColor = UIColorClear;
    [withdrawalTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(0);
        make.right.offset(0);
        make.height.mas_equalTo(44);
        make.top.offset(44);
        make.bottom.offset(-(44));
    }];
    _withdrawalTF = withdrawalTF;
    [withdrawalTF addTarget:self action:@selector(textChangeValue:) forControlEvents:UIControlEventEditingChanged];
    
    
    QMUIButton *allBtn = [[QMUIButton alloc] init];
    [allBtn setTitle:Localized(@"shop_withdrawalAll") forState:UIControlStateNormal];
    [allBtn setTitleColor:kColorMain forState:UIControlStateNormal];
    allBtn.titleLabel.font = [UIFont fontM:12];
    [withdrawalBG addSubview:allBtn];
    [allBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.offset(-20);
        make.height.mas_equalTo(44);
        make.bottom.offset(0);
    }];
    [allBtn addTarget:self action:@selector(toAllin) forControlEvents:UIControlEventTouchUpInside];
    
    QMUILabel *balanceL = [BRToolsView br_label:Localized(@"shop_balance") textColor:kColorTitle66B font:[UIFont fontM:12]];
    [withdrawalBG addSubview:balanceL];
    [balanceL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allBtn.mas_centerY).offset(0);
        make.left.offset(20);
    }];
    _balanceL = balanceL;
    balanceL.text = [NSString stringWithFormat:@"%@: %@",Localized(@"shop_balance"),[BRPayManager br_amount:self.withdrawalAmount]];
    
    QMUILabel *symoL = [BRToolsView br_label:USERManager.priceSymbol textColor:kColorTitle font:[UIFont fontM:20]];
    [withdrawalTF addSubview:symoL];
    [symoL mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.offset(0);
        make.left.offset(20);
    }];
    
    UIView *line = [BRToolsView getLineView];
    [withdrawalTF addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(20);
        make.right.offset(-20);
        make.bottom.offset(0);
        make.height.mas_equalTo(0.5);
    }];
    // ----优化输入框位置---
    [symoL sizeToFit];
    CGFloat w = symoL.mj_textWidth;
    
    withdrawalTF.textInsets = UIEdgeInsetsMake(0, w + 24, 0, 40);
    // -------提交按钮--------
    QMUIButton *submitBtn = [BRToolsView br_btnBGImg:Localized(@"shop_withdrawal")];
    [self.view addSubview:submitBtn];
    [submitBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(14);
        make.right.offset(-14);
        make.bottom.offset(-(14 + kSafeAreaBottomHeight));
        make.height.mas_equalTo(52);
    }];
    [submitBtn addTarget:self action:@selector(toWithdrawalBalance) forControlEvents:UIControlEventTouchUpInside];
    submitBtn.enabled = NO;
    _submitBtn = submitBtn;
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
